package util;

import java.util.ArrayList;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

import data.CheeseData;

public class CheeseRequester
{
    public static ArrayList<CheeseData> allCheeses = new ArrayList<CheeseData>();
    
    public CheeseRequester(){
        queryCheese();
    }
    
//    public static void main(String args[]){
//        queryCheese();
//        System.out.println("TOTAL CHEESES: "+allCheeses.size());
//        for(int i=0;i<allCheeses.size();i++){
//            System.out.println(allCheeses.get( i ).getName()+" "+allCheeses.get( i ).getDescrip()+" "+allCheeses.get( i ).getRegion()+" ");
//        }
//    }
    
    public static void queryCheese(){
        String sparqlQueryString = 
            "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
            "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/> " +
            "PREFIX dbpprop: <http://dbpedia.org/property/> "+
            "PREFIX yago: <http://dbpedia.org/class/yago/> "+
            "SELECT ?name ?descrip ?country " +
            "WHERE {" +
            "      ?name rdf:type yago:Cheese107850329 . " +
            "      ?name dbpedia-owl:abstract ?descrip . "+
            "      ?name dbpprop:country ?country . "+
            "      FILTER (lang(?descrip) = \"en\") " +
            "      }";
        
        Query query = QueryFactory.create(sparqlQueryString);
        QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);

        ResultSet results = qexec.execSelect();
        

        while(results.hasNext()){
            QuerySolution result= results.next();
            String descrip= result.getLiteral( "?descrip" ).toString();
            descrip= descrip.substring( 0, descrip.length()-3 ); //get rid of @en
            String region =result.getLiteral( "?country" ).toString();
            region = region.substring( 0, region.length()-3 );//get rid of @en
            String name= result.getResource( "?name" ).toString();
            name = name.substring( name.lastIndexOf( "/")+1, name.length() );
            CheeseData cheese= new CheeseData(name,region,descrip);
            allCheeses.add( cheese );
        }
         
        

       qexec.close() ;
    }

    public ArrayList<CheeseData> getAllCheeses() {
        return allCheeses;
    }

}
